
package org.csu.molediary.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.molediary.api.common.CommonResponse;
import org.csu.molediary.api.entity.Account;
import org.csu.molediary.api.entity.Diary;
import org.csu.molediary.api.entity.Tag;
import org.csu.molediary.api.persistence.AccountMapper;
import org.csu.molediary.api.persistence.DiaryMapper;
import org.csu.molediary.api.persistence.TagMapper;
import org.csu.molediary.api.service.TagService;
import org.csu.molediary.api.vo.DiaryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service("TagService")
public class TagServiceImpl implements TagService {

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private DiaryMapper diaryMapper;

    @Autowired
    private AccountMapper accountMapper;

    @Override
    //获得所有话题
    public CommonResponse<List<Tag>> getAllTags() {
        List<Tag> tagList = tagMapper.selectList(null);
        if(tagList.isEmpty()){
            return CommonResponse.createForError("获取所有的话题异常");
        }
        return CommonResponse.createForSuccess("获取所有话题成功",tagList);
    }

    @Override
    //获得某话题下所有日记
    public CommonResponse<List<DiaryVO>> getDiaryByTagid(int tagid) {
        QueryWrapper<Diary> diaryQueryWrapper = new QueryWrapper<>();
        diaryQueryWrapper.eq("tagid",tagid);
        List<Diary> diaryList = diaryMapper.selectList(diaryQueryWrapper);
        List<DiaryVO> diaryVOList = new ArrayList<>();

        //为DiaryVOList插入Diary对象
        Iterator<Diary> diaryIterator = diaryList.iterator();
        while(diaryIterator.hasNext()) {
            Diary diary = diaryIterator.next();
            DiaryVO diaryVO = new DiaryVO();

            diaryVO.setDiary(diary);
            QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
            accountQueryWrapper.eq("id",diary.getAccountid());
            Account account = accountMapper.selectOne(accountQueryWrapper);

            diaryVO.setHead(account.getHead());
            diaryVO.setName(account.getName());

            diaryVOList.add(diaryVO);
        }
        if(diaryVOList.isEmpty()){
            return CommonResponse.createForError("获得某话题下所有日记异常");
        }
        return CommonResponse.createForSuccess("获得某话题下所有日记成功",diaryVOList);
    }

    @Override
    public CommonResponse<Tag> getTagByTagContent(String tagcontent) {
        QueryWrapper<Tag> tagQueryWrapper=new QueryWrapper<>();
        tagQueryWrapper.eq("tagcontent",tagcontent);
        Tag tag=tagMapper.selectOne(tagQueryWrapper);

        if(tag.getTagcontent()!=null)
            return CommonResponse.createForSuccess(tag);
        else
            return CommonResponse.createForSuccessMessage("找不到话题");
    }

}

